@echo off
echo ========================================
echo    APK Build Script
echo ========================================
echo.

:: Set working directory
set PROJECT_DIR=%~dp0
set APK_OUTPUT_DIR=%PROJECT_DIR%app\build\outputs\apk\debug

echo [1/3] Checking project environment...
if not exist "%PROJECT_DIR%gradlew.bat" (
    echo ERROR: gradlew.bat not found
    echo Please make sure script is in Android project root
    pause
    exit /b 1
)
echo OK: Project environment check passed
echo.

echo [2/3] Cleaning project and building APK...
echo Cleaning project...
call gradlew.bat clean
if %ERRORLEVEL% NEQ 0 (
    echo ERROR: Failed to clean project
    pause
    exit /b 1
)

echo.
echo Building Debug APK...
call gradlew.bat assembleDebug
if %ERRORLEVEL% NEQ 0 (
    echo ERROR: Failed to build APK
    pause
    exit /b 1
)
echo.

echo [3/3] Checking build results...
if exist "%APK_OUTPUT_DIR%\app-debug.apk" (
    echo SUCCESS: APK built successfully!
    echo.
    echo APK Information:
    for %%F in ("%APK_OUTPUT_DIR%\app-debug.apk") do (
        echo   File: %%F
        echo   Size: %%~zF bytes
    )
    echo.
    echo Output Directory: %APK_OUTPUT_DIR%
    echo.
    echo Tips:
    echo   - Transfer this APK to Android device for installation
    echo   - Camera permission required during installation
    echo   - For Release version, run: gradlew.bat assembleRelease
    echo.

    :: Ask to open output directory
    set /p OPEN_DIR="Open APK output directory? (Y/N): "
    if /i "%OPEN_DIR%"=="Y" (
        explorer "%APK_OUTPUT_DIR%"
    )
) else (
    echo ERROR: APK file not found
    echo Please check error messages in build log
    pause
    exit /b 1
)

echo.
echo ========================================
echo    Build Complete!
echo ========================================
echo.
pause